package com.suieqian.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.suieqian.config.Env;
import com.suieqian.dto.req.RoleReq;
import com.suieqian.dto.resp.RoleResp;
import com.suieqian.dto.resp.UserRoleRefCheckedResp;
import com.suieqian.entity.Role;
import com.suieqian.entity.UserRoleRef;
import com.suieqian.enums.DelStatusEnum;
import com.suieqian.service.IRoleService;
import com.suieqian.service.IUserRoleRefService;
import com.suieqian.util.Message;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 角色管理
 *
 * @author lirch
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("api/roleController")
@Slf4j
public class RoleController {

    @Resource
    private IRoleService roleService;

    @Resource
    private IUserRoleRefService userRoleRefService;

    @ApiOperation("角色分页列表")
    @RequestMapping(value = "/listPage", method = RequestMethod.POST)
    public Message<Message.PageResp<RoleResp>> listPage(RoleReq roleReq) {
        try {
            IPage<Role> page = new Page<>(roleReq.getPageNo(), roleReq.getPageSize());
            LambdaQueryWrapper<Role> lqw = Wrappers.lambdaQuery();
            lqw.eq(Role::getDelStatus, DelStatusEnum.NORMAL.getCode())
                    .like(StrUtil.isNotBlank(roleReq.getRoleName()), Role::getRoleName, roleReq.getRoleName())
                    .orderByDesc(Role::getRoleId);
            IPage<Role> rsPage = roleService.page(page, lqw);
            return Message.success(rsPage, RoleResp.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Message.error("获取用户列表失败");
        }
    }

    @ApiOperation("角色与选中角色列表")
    @RequestMapping(value = "/listRoleWithChecked", method = RequestMethod.GET)
    public Message<UserRoleRefCheckedResp> listRoleWithChecked(@RequestParam(value = "userId", required = false) @ApiParam(value = "用户id", required = false) Long userId) {
        try {
            LambdaQueryWrapper<Role> lqw = Wrappers.lambdaQuery();
            lqw.eq(Role::getDelStatus, DelStatusEnum.NORMAL.getCode())
                    .orderByDesc(Role::getRoleId);
            List<Role> roleList = roleService.list(lqw);
            if (CollUtil.isEmpty(roleList)) {
                return Message.success(null);
            }
            UserRoleRefCheckedResp userRoleRefCheckedResp = new UserRoleRefCheckedResp();

            List<RoleResp> roleRespList = BeanUtil.copyToList(roleList, RoleResp.class);
            if (Objects.nonNull(userId)) {
                LambdaQueryWrapper<UserRoleRef> lqwu = Wrappers.lambdaQuery();
                lqwu.eq(UserRoleRef::getUserId, userId);
                List<UserRoleRef> userRoleRefList = userRoleRefService.list(lqwu);
                if (CollUtil.isNotEmpty(userRoleRefList)) {
                    userRoleRefCheckedResp.setCheckedRoleIdList(userRoleRefList.stream().map(item -> item.getRoleId()).collect(Collectors.toSet()).stream().collect(Collectors.toList()));
                }
            }
            userRoleRefCheckedResp.setRoleRespList(roleRespList);
            return Message.success(userRoleRefCheckedResp);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Message.error("获取用户列表失败");
        }
    }

    @ApiOperation("添加角色")
    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    public Message<Boolean> addRole(RoleReq roleReq) {
        Preconditions.checkArgument(StrUtil.isNotBlank(roleReq.getRoleName()), "角色名不能为空");
        try {
            Role role = new Role();
            BeanUtil.copyProperties(roleReq, role);
            role.setCreateTime(LocalDateTime.now())
                    .setCreateId(Env.getUser().getUserId())
                    .setUpdateName(Env.getUser().getUserAccount())
                    .setUpdateId(Env.getUser().getUserId())
                    .setUpdateTime(LocalDateTime.now())
                    .setDelStatus(DelStatusEnum.NORMAL.getCode());
            roleService.save(role);
            return Message.success(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Message.error("角色添加失败");
        }
    }

    @ApiOperation("编辑角色")
    @RequestMapping(value = "/modRole", method = RequestMethod.POST)
    public Message<Boolean> modRole(RoleReq roleReq) {
        Preconditions.checkArgument(Objects.nonNull(roleReq.getRoleId()), "角色ID不能为空");
        Preconditions.checkArgument(StrUtil.isNotBlank(roleReq.getRoleName()), "角色名不能为空");
        try {
            Role role = new Role();
            BeanUtil.copyProperties(roleReq, role);
            role.setCreateTime(LocalDateTime.now())
                    .setUpdateName(Env.getUser().getUserAccount())
                    .setUpdateId(Env.getUser().getUserId())
                    .setUpdateTime(LocalDateTime.now());
            Boolean flag = roleService.updateById(role);
            if (flag) {
                return Message.success(flag);
            }
            return Message.error("角色编辑失败");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Message.error("角色编辑失败");
        }
    }

    @ApiOperation("删除角色")
    @RequestMapping(value = "/deleteRole", method = RequestMethod.POST)
    public Message deleteRole(Long roleId) {
        Preconditions.checkArgument(Objects.nonNull(roleId), "角色id不能为空");
        try {
            Role role = roleService.getById(roleId);
            if (Objects.isNull(role)) {
                return Message.error(Message.PARAMETER_ERROR, "角色id非法");
            }
            role.setDelStatus(DelStatusEnum.ERROR.getCode())
                    .setUpdateName(Env.getUser().getUserAccount())
                    .setUpdateId(Env.getUser().getUserId())
                    .setUpdateTime(LocalDateTime.now());
            roleService.updateById(role);
            return Message.success("角色删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Message.error("角色删除失败");
        }
    }

}
